
package com.quartet.modules.system.rest;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quartet.annotation.Log;
import com.quartet.api.ApiResult;
import com.quartet.api.MapServerException;
import com.quartet.api.PageResult;
import com.quartet.api.ResultErrorEnum;
import com.quartet.exception.BadRequestException;
import com.quartet.modules.system.domain.Role;
import com.quartet.modules.system.dto.RoleQueryDto;
import com.quartet.modules.system.service.RoleService;
import com.quartet.modules.system.service.dto.RoleDto;
import com.quartet.modules.system.service.dto.RoleQueryCriteria;
import com.quartet.modules.system.service.dto.RoleSmallDto;
import com.quartet.modules.user.entity.TUserInfo;
import com.quartet.modules.user.service.TUserInfoService;
import com.quartet.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-12-03
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "系统：角色管理")
@RequestMapping("/api/roles")
public class RoleController {

    private final RoleService roleService;
    private final TUserInfoService tUserInfoService;

    private static final String ENTITY_NAME = "role";

    @ApiOperation("获取单个role")
    @GetMapping(value = "/{id}")
//    @PreAuthorize("@el.check('roles:list')")
    public ApiResult<RoleDto> query(@PathVariable Long id) {
        return ApiResult.ok(roleService.findById(id));
    }

    @ApiOperation("导出角色数据")
    @GetMapping(value = "/download")
//    @PreAuthorize("@el.check('role:list')")
    public void download(HttpServletResponse response, RoleQueryCriteria criteria) throws IOException {
        roleService.download(roleService.queryAll(criteria), response);
    }

    @ApiOperation("分页查询角色信息")
    @PostMapping(value = "/all")
//    @PreAuthorize("@el.check('roles:list','user:add','user:edit')")
    public ApiResult<PageResult<RoleDto>> query(@RequestBody RoleQueryDto roleQueryDto) {
        List<RoleDto> roleDtoList = roleService.queryAll();
        PageResult<RoleDto> pageResult = new PageResult<>();
        pageResult.setTotal((long) roleDtoList.size());
        List<RoleDto> roleDtos = roleDtoList.stream().filter(roleDto -> roleDto.getName().contains(roleQueryDto.getRoleName()))
                .skip((roleQueryDto.getCurrent() - 1) * roleQueryDto.getLimit()).limit(roleQueryDto.getLimit()).collect(Collectors.toList());
        pageResult.setData(roleDtos);
        return ApiResult.ok(pageResult);
    }

    @ApiOperation("查询角色")
    @GetMapping
//    @PreAuthorize("@el.check('roles:list')")
    public ApiResult query(RoleQueryCriteria criteria, Pageable pageable) {
        return ApiResult.ok(roleService.queryAll(criteria, pageable));
    }

    @ApiOperation("获取用户级别")
    @GetMapping(value = "/level")
    public ResponseEntity<Object> getLevel() {
        return new ResponseEntity<>(Dict.create().set("level", getLevels(null)), HttpStatus.OK);
    }

    @Log("新增角色")
    @ApiOperation("新增角色")
    @PostMapping
//    @PreAuthorize("@el.check('roles:add')")
    public ApiResult<RoleDto> create(@Validated @RequestBody Role resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
//        getLevels(resources.getLevel());
        Role role = roleService.create(resources);
        RoleDto roleDto = BeanUtil.copyProperties(role, RoleDto.class);
        return ApiResult.ok(roleDto);
    }

    @Log("修改角色")
    @ApiOperation("修改角色")
    @PutMapping
//    @PreAuthorize("@el.check('roles:edit')")
    public ApiResult update(@Validated(Role.Update.class) @RequestBody Role resources) {
//        getLevels(resources.getLevel());
        roleService.update(resources);
        return ApiResult.ok();
    }

    @Log("修改角色菜单")
    @ApiOperation("修改角色菜单")
    @PutMapping(value = "/menu")
//    @PreAuthorize("@el.check('roles:edit')")
    public ApiResult updateMenu(@RequestBody Role resources) {
        RoleDto role = roleService.findById(resources.getId());
//        getLevels(role.getLevel());
        roleService.updateMenu(resources, role);
        return ApiResult.ok();
    }

    @Log("删除角色")
    @ApiOperation("删除角色")
    @DeleteMapping
//    @PreAuthorize("@el.check('roles:del')")
    public ApiResult delete(@RequestBody Set<Long> ids) {
//        for (Long id : ids) {
//            RoleDto role = roleService.findById(id);
//            getLevels(role.getLevel());
//        }
        // 验证是否被用户关联
//        roleService.verification(ids);
        QueryWrapper<TUserInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().in(TUserInfo::getRoleId,ids);
        int count = tUserInfoService.count(queryWrapper);
        if (count>0){
            throw new MapServerException(ResultErrorEnum.ROKPM001);
        }
        roleService.delete(ids);
        return ApiResult.ok();
    }

    @ApiOperation("查询角色下拉框")
    @GetMapping("/queryRoleList")
//    @PreAuthorize("@el.check('roles:list')")
    public ApiResult queryRoleList() {
        return ApiResult.ok(roleService.queryAll());
    }

    /**
     * 获取用户的角色级别
     *
     * @return /
     */
    private int getLevels(Integer level) {
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        if (level != null) {
            if (level < min) {
                throw new BadRequestException("权限不足，你的角色级别：" + min + "，低于操作的角色级别：" + level);
            }
        }
        return min;
    }
}
